package com.nulldev.util.web.dns.server.server.resolver;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.web.dns.server.message.DNSQuestion;
import com.nulldev.util.web.dns.server.message.DNSRecord;
import com.nulldev.util.web.dns.server.message.DNSRecordType;

public class SimpleResolver implements DNSResolver {
	private final Logger logger = LoggerFactory.getLogger(SimpleResolver.class);

    private Map<DNSRecordType, DNSRecord> records = new HashMap<DNSRecordType, DNSRecord>();

    /**
     * Fetches DNS records from a map based on type of the question.
     * @param question
     * @return
     */
    @Override
    public List<DNSRecord> resolve(DNSQuestion question) {
        logger.debug("Attempting to resolve {}", question);
        DNSRecord answer = records.get(question.getQuestionType());
        if (null == answer) {
            logger.debug("Unable to resolve, returning empty list");
            return Collections.emptyList();
        } else {
            logger.debug("Answer found {}", answer);
            return Collections.singletonList(answer);
        }
    }

    /**
     * Get the DNS record for a given type.
     * @param recordType
     * @return
     */
    public DNSRecord getDnsRecord(DNSRecordType recordType) {
        return records.get(recordType);
    }

    /**
     * Set the DNS record for a given type.
     * @param recordType
     * @param record
     */
    public void setDnsRecord(DNSRecordType recordType, DNSRecord record) {
        logger.debug("Setting record {} for record type {}", record, recordType);
        records.put(recordType, record);
    }
}
